package com.nkym.utils;/*
 * @ClassName AESUtil
 * @Desc TODO
 * @Author 19637
 * @Date 2023/5/21 1:09
 * @Version 1.0
 */

import cn.hutool.crypto.symmetric.AES;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * AES: Advanced Encryption Standard 高级加密标准
 * 最常见的对称加密算法，即加密和解密使用同样的密钥，加密结果可逆
 * 特点：加密速度非常快，适合经常发送数据的场合
 */
public class AESUtil {

    public static void main(String[] args) {
    }

    //加密
    public static String encrypt(String data, String key,String iv) throws DecoderException {
        byte[] keyBytes = Hex.decodeHex(key);
        byte[] bytes = Hex.decodeHex(iv);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        AES aes = new AES("CBC", "PKCS7Padding",
                // 密钥，可以自定义
                keyBytes,
                // iv加盐，按照实际需求添加
                bytes);
        String encryptHex = aes.encryptBase64(data);
        return encryptHex;
    }

    //解密
    public static String decrypt(String encryptData, String key,String iv) throws DecoderException {
        byte[] keyBytes = Hex.decodeHex(key);
        byte[] bytes = Hex.decodeHex(iv);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        AES aes = new AES("CBC", "PKCS7Padding",
                // 密钥，可以自定义
                keyBytes,
                // iv加盐，按照实际需求添加
                bytes);
        String decryptedText = aes.decryptStr(encryptData);
        return decryptedText;
    }
}
